package com.taotao.sso.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbUserMapper;
import com.taotao.pojo.TbUser;
import com.taotao.pojo.TbUserExample;
import com.taotao.pojo.TbUserExample.Criteria;

@Service
public class RegisterServiceImpl implements RegisterService {
	@Autowired
	private TbUserMapper tbUserMapper;

	/**
	 * 注册数据校验方法
	 */
	@Override
	public TaotaoResult checkData(String param, int type) {
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		// 判断参数类型 1=username;2=phone;3=email
		// 如果type==其它 ,则example为空,则查询所有肯定有数据,返回false
		if (type == 1) {
			criteria.andUsernameEqualTo(param);
		} else if (type == 2) {
			criteria.andPhoneEqualTo(param);
		} else if (type == 3) {
			criteria.andEmailEqualTo(param);
		}
		// 取到user信息
		List<TbUser> list = tbUserMapper.selectByExample(example);
		// 判断list是否为空,为空说明数据不存在,可以创建;不为空已经存在,保证唯一性不可创建
		if (list == null || list.isEmpty()) {
			return TaotaoResult.ok(true);
		}
		return TaotaoResult.ok(false);
	}

	@Override
	public TaotaoResult register(TbUser tbUser) {
		String username = tbUser.getUsername();
		String password = tbUser.getPassword();
		// 数据校验
		// 用户名和密码不能为空
		if (username.isEmpty() || password.isEmpty()) {
			return TaotaoResult.build(400, "用户名或密码不能为空");
		}
		if (password.length() < 7) {
			return TaotaoResult.build(400, "密码最少为7位的数字或字母组合");
		}

		// 判断数据是否存在
		if (!(boolean) checkData(username, 1).getData()) {
			return TaotaoResult.build(400, "用户已存在");
		}
		if (tbUser.getPhone() != null) {
			if (!(boolean) checkData(tbUser.getPhone(), 2).getData()) {
				return TaotaoResult.build(400, "手机号码已注册");
			}
		}
		if (tbUser.getEmail() != null) {
			if (!(boolean) checkData(tbUser.getEmail(), 3).getData()) {
				return TaotaoResult.build(400, "邮箱已注册");
			}
		}
		tbUser.setUpdated(new Date());
		tbUser.setCreated(new Date());
		// 密码加密MD5
		String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
		tbUser.setPassword(md5password);
		// 执行插入
		tbUserMapper.insertSelective(tbUser);

		return TaotaoResult.ok();
	}

}
